﻿using System.Collections.Generic;
using Helpers;
using MarriageFertility.Actions;
using TaleWorlds.CampaignSystem;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.Party;

namespace MarriageFertility.Helpers;

public static class RelationHelper
{
    public static bool HotButterFound = false;

    public static bool HasFamilyRelation(Hero baseHero, Hero queriedHero) =>
        IsHusband(baseHero, queriedHero) || IsWife(baseHero, queriedHero) || IsHusbandMother(baseHero, queriedHero)
        || IsWifeFather(baseHero, queriedHero) || IsWifeMother(baseHero, queriedHero)
        || IsExHusband(baseHero, queriedHero) || IsExWife(baseHero, queriedHero);

    public static bool IsHusbandFather(Hero baseHero, Hero queriedHero)
    {
        if (baseHero.Spouse == null || baseHero.Spouse.IsFemale) return false;
        return baseHero.Spouse.Father == queriedHero;
    }

    public static bool IsHusbandMother(Hero baseHero, Hero queriedHero)
    {
        if (baseHero.Spouse == null || baseHero.Spouse.IsFemale) return false;
        return baseHero.Spouse.Mother == queriedHero;
    }

    public static bool IsWifeFather(Hero baseHero, Hero queriedHero)
    {
        if (baseHero.Spouse == null || !baseHero.Spouse.IsFemale) return false;
        return baseHero.Spouse.Father == queriedHero;
    }

    public static bool IsWifeMother(Hero baseHero, Hero queriedHero)
    {
        if (baseHero.Spouse == null || !baseHero.Spouse.IsFemale) return false;
        return baseHero.Spouse.Mother == queriedHero;
    }

    public static bool IsHusband(Hero baseHero, Hero queriedHero)
    {
        return baseHero.Spouse != null && baseHero.Spouse == queriedHero && !queriedHero.IsFemale;
    }

    public static bool IsWife(Hero baseHero, Hero queriedHero)
    {
        return baseHero.Spouse != null && baseHero.Spouse == queriedHero && queriedHero.IsFemale;
    }

    public static bool IsExHusband(Hero baseHero, Hero queriedHero)
    {
        return baseHero.Spouse != null && baseHero.ExSpouses.Contains(queriedHero) && !queriedHero.IsFemale;
    }

    public static bool IsExWife(Hero baseHero, Hero queriedHero)
    {
        return baseHero.Spouse != null && baseHero.ExSpouses.Contains(queriedHero) && queriedHero.IsFemale;
    }

    public static void SetSpouse(Hero hero)
    {
        if (hero != null)
        {
            Hero.MainHero.ExSpouses.Remove(hero);
            Hero.MainHero.Spouse = hero;
            hero.Spouse = Hero.MainHero;
            Hero.MainHero.ExSpouses.Remove(hero);
            hero.ExSpouses.Remove(Hero.MainHero);
            ChangeRelationAction.ApplyPlayerRelation(hero, 10);
        }
    }
    public static void NameLessNPCToSpouse(CharacterObject character, CampaignGameStarter campaignGameStarter)
    {
        Hero hero = GenerateHeroFromConversationCharacter(character, campaignGameStarter);
        if (hero != null)
        {
            hero.SetNewOccupation(Occupation.Lord);
            hero.Clan=Clan.PlayerClan;
            Hero.MainHero.ForceMarry(hero);
            hero.CompanionOf = null;
        }
    }
		
    public static void NameLessNPCToLord(CharacterObject character, CampaignGameStarter campaignGameStarter)
    {
        Hero hero = GenerateHeroFromConversationCharacter(character, campaignGameStarter);
        hero.SetNewOccupation(Occupation.Lord);
        hero.Clan=Clan.PlayerClan;
        if (!MobileParty.MainParty.MemberRoster.Contains(hero.CharacterObject))
        {
            MobileParty.MainParty.MemberRoster.AddToCounts(hero.CharacterObject, 1, false, 0, 0, true, -1);
        }
    }
		
		
    private static Hero GenerateHeroFromConversationCharacter(CharacterObject target, CampaignGameStarter campaignGameStarter)
    {
        if (target == null) return null;
        
        Hero hero = HeroCreator.CreateSpecialHero(
            target, 
            null, 
            Clan.PlayerClan, 
            Clan.PlayerClan
        );
        
        hero.ChangeState(Hero.CharacterStates.Active);
        hero.UpdateLastKnownClosestSettlement(hero.HomeSettlement);
        HeroInitPropertyUtils.InitHeroForNPC(hero);
    
        // 加入玩家队伍并触发事件
        AddHeroToPartyAction.Apply(hero, MobileParty.MainParty);
        CampaignEventDispatcher.Instance.OnHeroCreated(hero);
    
        // 更新对话系统
        ConversationUtils.ChangeCurrentCharaObject(campaignGameStarter, hero);
    
        // 年龄修正逻辑
        if (hero.Age > 30f)
        {
            hero.SetBirthDay(HeroHelper.GetRandomBirthDayForAge(22f));
        }
        return hero;
    }
    
    
    public static Hero FindAncestorOf(Hero hero)
    {
        // 1. 收集符合条件的父母（最多2个元素）
        var parents = new List<Hero>(2);
        if (hero.Father?.Clan != null) parents.Add(hero.Father);
        if (hero.Mother?.Clan != null) parents.Add(hero.Mother);

        // 2. 按优先级检查每个条件（从最高优先级开始）
        foreach (var parent in parents)
        {
            if (parent.Clan.Kingdom?.Leader == parent) 
                return FindAncestorOf(parent);
        }
    
        foreach (var parent in parents)
        {
            if (parent.Clan.Kingdom?.RulingClan == parent.Clan) 
                return FindAncestorOf(parent);
        }
    
        foreach (var parent in parents)
        {
            if (parent.MapFaction?.IsKingdomFaction == true && parent.IsFactionLeader) 
                return FindAncestorOf(parent);
        }
    
        foreach (var parent in parents)
        {
            if (parent.MapFaction?.IsKingdomFaction == true) 
                return FindAncestorOf(parent);
        }
    
        foreach (var parent in parents)
        {
            if (parent.Clan.IsMinorFaction && parent.IsFactionLeader) 
                return FindAncestorOf(parent);
        }
    
        foreach (var parent in parents)
        {
            if (parent.Clan.IsMinorFaction) 
                return FindAncestorOf(parent);
        }
    
        foreach (var parent in parents)
        {
            if (parent.Clan.Leader == parent) 
                return FindAncestorOf(parent);
        }
        return parents.Count > 0 ? FindAncestorOf(parents[0]) : hero; 
    }
}